<template>
  <el-form ref="ruleForm" :model="goodsPhotos">
    <headline :headline="'商品图片'">
      <span slot="head">
        <el-button type="text" @click="advertisingGuidelines">点击查看《沃尔玛大卖场电商图片标准》</el-button>
        <el-button v-if="fromPage == 'commodityLibrary'" type="text" @click="onLoadeImgs">点击下载商品图片</el-button>
      </span>
    </headline>

    <el-form-item style="padding-top: 10px" class="content-photo" prop="skuResourcesImg" :rules="{ validator: validator, trigger: 'change' }">
      <div class="title">
        <span>商品主图</span>
        <span v-if="resourceDiffFlag.length" class="attention-tips">
          注意：
          <span v-for="item in resourceDiffFlag" :key="item.channalId" class="el-button--text" @click="goJump(item.channalId)"> {{ item.channalName }}</span>
          渠道的图片不一样。点击查看
        </span>
      </div>
      <div class="uploadPhoto">
        <draggable
          v-model="goodsPhotos.skuResourcesImg"
          draggable=".elImg"
          :disabled="isDisabled"
          :group="groupName.skuResourcesImg"
          animation="200"
          @choose="(e) => imgChoose(e, 'skuResourcesImg')"
          @end="transEnd"
        >
          <transition-group class="transition-group">
            <div v-for="(img) in goodsPhotos.skuResourcesImg" :key="img.resourceUrl" class="elImg" :resourceType="img.resourceType">
              <el-image :src="img.resourceUrl | transImgUrl" :preview-src-list="goodsPhotos.skuResourcesImg | transUrlName" />
              <div v-if="!isDisabled" class="del" @click="delSkuResources(img, 1)">
                <i class="el-icon-delete" />
              </div>
            </div>
          </transition-group>
        </draggable>
        <el-upload
          v-if="goodsPhotos.skuResourcesImg.length < 9 && !isDisabled"
          :auto-upload="false"
          multiple
          accept=".jpg,.jpeg"
          :on-change="
            (file, fileList) => {
              handleOnChange(file, fileList, 1)
            }
          "
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
        >
          <i class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </div>
      <div class="tip">标准建品主图至少需要6张，简单建品至少需要一张，图片尺寸：不低于800px*800px，仅支持JPG格式，大小不超过3MB，您可以拖拽图片调整顺序：</div>
    </el-form-item>

    <el-form-item class="content-photo" prop="skuOptionResources" :rules="{ validator: validator2, trigger: 'change' }">
      <div class="title">商品素材图</div>
      <div class="uploadPhoto">
        <draggable
          v-model="goodsPhotos.skuOptionResources"
          draggable=".elImg"
          :disabled="isDisabled"
          :group="groupName.skuOptionResources"
          animation="300"
          @choose="(e) => imgChoose(e, 'skuOptionResources')"
          @end="transEnd"
        >
          <transition-group class="transition-group">
            <div v-for="(img) in goodsPhotos.skuOptionResources" :key="img.resourceUrl" class="elImg" :resourceType="img.resourceType">
              <el-image :src="img.resourceUrl | transImgUrl" :preview-src-list="goodsPhotos.skuOptionResources | transUrlName" />
              <div v-if="!isDisabled" class="del" @click="delSkuOptionResources(img)">
                <i class="el-icon-delete" />
              </div>
            </div>
          </transition-group>
        </draggable>
        <el-upload
          v-if="goodsPhotos.skuOptionResources.length < 30 && !isDisabled"
          :auto-upload="false"
          :on-change="handleOnChange2"
          class="avatar-uploader"
          action="#"
          accept=".png,.jpg,.jpeg"
          :show-file-list="false"
          multiple
        >
          <i class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </div>
      <div class="tip">素材图最多30张，图片尺寸：不低于800px*800px，仅支持JPG,PNG格式，大小不超过3MB</div>
    </el-form-item>

    <el-form-item class="content-photo" prop="transparentImg" :rules="{ validator: validator1, trigger: 'change' }">
      <div class="title">透明图</div>
      <div class="uploadPhoto">
        <draggable
          v-model="goodsPhotos.transparentImg"
          draggable=".elImg"
          :disabled="isDisabled"
          :group="groupName.transparentImg"
          animation="300"
          @choose="(e) => imgChoose(e, 'transparentImg')"
          @end="transEnd"
        >
          <transition-group class="transition-group">
            <div v-for="(img) in goodsPhotos.transparentImg" :key="img.resourceUrl" class="elImg" :resourceType="img.resourceType">
              <el-image :src="img.resourceUrl | transImgUrl" :preview-src-list="goodsPhotos.transparentImg | transUrlName" />
              <div v-if="!isDisabled" class="del" @click="delSkuResources(img, 3)">
                <i class="el-icon-delete" />
              </div>
            </div>
          </transition-group>
        </draggable>
        <el-upload
          v-if="!goodsPhotos.transparentImg.length && !isDisabled"
          :auto-upload="false"
          :on-change="
            (file, fileList) => {
              handleOnChange(file, fileList, 3)
            }
          "
          class="avatar-uploader"
          action="#"
          accept=".png"
          :show-file-list="false"
        >
          <i class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </div>
      <div class="tip">图片尺寸: 不低于800px*800px,仅支持PNG格式，大小不超过3MB, 图片需透明背景，需与前台展示首图一致（用现有首图抠图）</div>
    </el-form-item>
  </el-form>
</template>

<script>
import headline from '@/views/coi/components/headline.vue'
import { uploadSkuResource, uploadSkuOptionalResource, deleteSkuResource, deleteSkuOptionalResource, goodsInfosava } from '@/api/coi/onlineTaskAPI/sku'
import { uploadSkuChannelResource, deleteSkuChannelResource, commodityInfoSave } from '@/api/coi/onlineTaskAPI/sku'
import {getImgInfo} from '@/api/objectStorage'
import draggable from 'vuedraggable'
import eventBus from '@/utils/eventBus'
import { authentication } from '@/utils/processingData.js'

export default {
  components: {
    headline,
    draggable
  },
  filters: {
    transUrlName(imgArr) {
      return imgArr.map((e) => authentication(e.resourceUrl))
    },
    transImgUrl(url) {
      return authentication(url)
    }
  },
  props: {
    goodsPhotos: {
      type: Object,
      default: () => {
        return {
          skuOptionResources: [],
          transparentImg: [],
          skuResourcesImg: []
        }
      }
    },
    isDisabled: {
      type: Boolean,
      default: true
    },
    buildStandard: {
      type: Number,
      default: 0
    },
    fromPage: {
      type: String,
      default: 'making'
    },
    channelId: {
      type: String,
      default: ''
    },
    processId: {
      type: Number,
      default: 0
    },
    tab: {
      type: String,
      default: ''
    },
    resourceDiffFlag: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      isTrans: false,
      num: 0,
      validator: (rule, value, callback) => {
        if (this.buildStandard !== 1) {
          if (value.length < 6) callback(new Error('* 主图的数量少于6张'))
          else if (value.length > 9) callback(new Error('* 主图的数量大于9张'))
          else callback()
        } else if (this.buildStandard === 1 && value.length < 1) callback(new Error('* 主图的数量为空'))
        else callback()
      },
      validator1: (rule, value, callback) => {
        if (value.length !== 1) callback(new Error('* 商品透明图数量错误'))
        else callback()
      },
      validator2: (rule, value, callback) => {
        if (value.length < 1) callback(new Error('* 商品素材图数量为空'))
        else if (value.length > 30) callback(new Error('* 商品素材图数量超过30张'))
        else callback()
      },
      groupName: {
        transparentImg: 'transparentImg', // 透明图
        skuResourcesImg: 'skuResourcesImg', // 主图
        skuOptionResources: 'skuOptionResources' // 素材图
      }
    }
  },
  methods: {
    async imgChoose(e, type) {
      const flag = e && e.item && e.item.attributes && e.item.attributes.resourcetype && e.item.attributes.resourcetype.value
      // 检测当前的图片是不是主图或者透明图.佐证图无这个属性
      if (!flag) return
      // 当移动主图透明图时候检查下素材图是否过30张,校验通过改变组的名字让其可以移动
      if ((type === 'transparentImg' || type === 'skuResourcesImg') && this.goodsPhotos.skuOptionResources.length < 30) this.groupName.skuOptionResources = type
      // 移动素材图
      if (type === 'skuOptionResources') {
        try {
          let imgType = null
          const content = e.item
          const imgSrc = content?.querySelector('[src]')?.attributes?.src.value
          const uploadId = imgSrc?.slice(imgSrc.lastIndexOf('/'))
          if (!uploadId) throw new Error('截取不到图片的图片的uploadId')
          const {code, data} = await getImgInfo(uploadId)
          if (code !== '200') return
          const {uploadPath, essence} = data
          if (uploadPath) {
            const typeIndex = uploadPath.lastIndexOf('.')
            if (typeIndex === -1) return
            imgType = uploadPath.slice(typeIndex + 1)
          } else if (essence) {
            const typeIndex = essence.lastIndexOf('/')
            imgType = essence.slice(typeIndex + 1)
          }
          // 防止调皮的小朋友改尾缀大小写混着玩，统一转成大写去做判断
          if (['JPG', 'JPEG'].includes(imgType.toUpperCase()) && this.goodsPhotos?.skuResourcesImg?.length < 9) this.groupName.skuResourcesImg = type
          else if (['PNG'].includes(imgType.toUpperCase()) && this.goodsPhotos?.transparentImg?.length < 1) this.groupName.transparentImg = type
        } catch (error) {
          console.error(error)
          this.$message.error('查询不到该素材图文件信息，暂不能拖拽移动到主图/透明图，请手动下载后上传！')
        }
      }
    },
    transEnd() {
      this.isTrans = true
      this.groupName = {
        transparentImg: 'transparentImg', // 透明图
        skuResourcesImg: 'skuResourcesImg', // 主图
        skuOptionResources: 'skuOptionResources' // 素材图
      }
      if (this.fromPage === 'commodityLibrary') {
        this.$parent.operationCode[2] = 150
        eventBus.$emit('detailChange', true)
      }
    },
    async submit() {
      try {
        const info = JSON.parse(JSON.stringify(this.$parent.goodsInfo))
        const goodsPhotos = this.goodsPhotos
        goodsPhotos.skuResourcesImg.forEach((item, index) => {
          item.sort = index
        })
        if (this.fromPage === 'commodityLibrary') {
          goodsPhotos.skuResourcesImg.forEach((item, index) => {
            item.sort = index
            item.resourceType = 1
          })
          goodsPhotos.skuOptionResources.forEach((item, index) => {
            item.resourceType = 2
          })
          goodsPhotos.transparentImg.forEach((item, index) => {
            item.resourceType = 3
          })
          info.skuChannelInfos[0].skuResources = [...goodsPhotos.skuResourcesImg, ...goodsPhotos.transparentImg]
          info.skuChannelInfos[0].skuOptionResources = goodsPhotos.skuOptionResources
          info.imageUrl = goodsPhotos.skuResourcesImg[0].resourceUrl
        } else {
          info.skuResources = [...goodsPhotos.skuResourcesImg, ...goodsPhotos.transparentImg]
          info.skuOptionResources = goodsPhotos.skuOptionResources
        }
        info.skuChannelInfos.forEach((element) => {
          element.skuChannelInfo = JSON.stringify(element)
          delete element.categoryAttributeList
          delete element.channelAttributeList
        })
        const { result } = this.fromPage === 'commodityLibrary' ? await commodityInfoSave(info) : await goodsInfosava(info)
        return result
      } finally {
        console.log(this.result)
      }
    },
    submitForm() {
      let flag = null
      this.$refs.ruleForm.validate((valid) => {
        flag = valid
      })
      return flag
    },

    showMessage(message, type = 'success') {
      this.$message({
        message,
        type
      })
    },

    // 文件变动的钩子主图透明图
    async handleOnChange(file, fileList, type) {
      if (this.isTrans) await this.submit()
      this.isTrans = false
      setTimeout(() => {
        fileList.length = 0
      }, 200)
      if (type === 1) {
        if (fileList.length + this.goodsPhotos.skuResourcesImg.length > 9) {
          this.showMessage('图片的最大数量为9张！', 'error')
          return
        }
        if (file.raw.type !== 'image/jpg' && file.raw.type !== 'image/jpeg') {
          this.showMessage('仅支持上传jpg格式的图片！', 'error')
          return
        }
      } else {
        if (file.raw.type !== 'image/png') {
          this.$message({
            message: '仅支持上传png格式的图片！',
            type: 'error'
          })
          return
        }
      }
      var size = file.size / 1024 / 1024
      if (size > 3) {
        this.showMessage('图片大小大于3M', 'error')
        return
      }
      this.upload(file, type)
    },
    // 上传文件至服务器
    async upload(file, type) {
      try {
        this.num++
        eventBus.$emit('loadingChange', true)
        const formData = new FormData()
        formData.append('file', file.raw)
        if (this.fromPage === 'commodityLibrary') {
          formData.append('channelId', this.channelId)
          formData.append('processId', this.processId)
        } else {
          formData.append('skuId', this.$route.query.id)
        }
        formData.append('resourceType', type)
        const result = this.fromPage === 'commodityLibrary' ? await uploadSkuChannelResource(formData) : await uploadSkuResource(formData)
        if (result.code === '0') {
          if (this.fromPage === 'commodityLibrary') {
            this.$parent.operationCode[2] = 150
            eventBus.$emit('detailChange', true)
          }
          this.showMessage('图片上传成功')
          type === 1 ? this.goodsPhotos.skuResourcesImg.push(result.result) : this.goodsPhotos.transparentImg.push(result.result)
        }
      } finally {
        this.num--
        if (this.num === 0) eventBus.$emit('loadingChange', false)
      }
    },

    // 文件变动的钩子素材
    async handleOnChange2(file, fileList) {
      if (this.isTrans) await this.submit()
      this.isTrans = false
      setTimeout(() => {
        fileList.length = 0
      }, 200)
      if (fileList.length + this.goodsPhotos.skuOptionResources.length > 30) {
        this.showMessage('图片的最大数量为30张！', 'error')
        return
      }
      if (file.raw.type !== 'image/jpg' && file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
        this.showMessage('仅支持上传jpg/png格式的图片！', 'error')
        return
      }
      var size = file.size / 1024 / 1024
      if (size > 3) {
        this.showMessage('图片大小大于3M', 'error')
        return
      }
      this.upload2(file)
    },

    // 上传文件至服务器
    async upload2(file) {
      try {
        this.num++
        eventBus.$emit('loadingChange', true)
        const resourceType = file.raw.type === 'image/png' ? 3 : 1
        const formData = new FormData()
        formData.append('file', file.raw)
        if (this.fromPage === 'commodityLibrary') {
          formData.append('channelId', this.channelId)
          formData.append('processId', this.processId)
          formData.append('resourceType', 2)
        } else {
          formData.append('skuId', this.$route.query.id)
          formData.append('resourceType', resourceType)
        }
        const result = this.fromPage === 'commodityLibrary' ? await uploadSkuChannelResource(formData) : await uploadSkuOptionalResource(formData)
        if (result.code === '0') {
          if (this.fromPage === 'commodityLibrary') {
            this.$parent.operationCode[2] = 150
            eventBus.$emit('detailChange', true)
          }
          this.showMessage('图片上传成功')
          this.goodsPhotos.skuOptionResources.push(result.result)
        }
      } finally {
        this.num--
        if (this.num === 0) eventBus.$emit('loadingChange', false)
      }
    },

    // 删除主图透明图
    async delSkuResources(img, type) {
      let param = {
        skuId: this.$route.query.id - 0,
        url: img.resourceUrl
      }
      if (this.fromPage === 'commodityLibrary') {
        param = {
          channelId: this.channelId,
          resourceUrl: img.resourceUrl,
          processId: this.processId,
          resourceType: type
        }
      }
      const { result } =
        this.fromPage === 'commodityLibrary'
          ? await deleteSkuChannelResource(param)
          : await deleteSkuResource({ skuId: this.$route.query.id - 0, url: img.resourceUrl })
      if (result) {
        this.$message({
          message: result,
          type: 'success'
        })
        if (this.fromPage === 'commodityLibrary') {
          this.$parent.operationCode[2] = 150
          eventBus.$emit('detailChange', true)
        }
        const index =
          type === 1
            ? this.goodsPhotos.skuResourcesImg.findIndex((item) => item.id === img.id)
            : this.goodsPhotos.transparentImg.findIndex((item) => item.id === img.id)
        type === 1 ? this.goodsPhotos.skuResourcesImg.splice(index, 1) : this.goodsPhotos.transparentImg.splice(index, 1)
      }
    },

    // 删除素材图
    async delSkuOptionResources(img) {
      let param = {
        skuId: this.$route.query.id - 0,
        url: img.resourceUrl
      }
      if (this.fromPage === 'commodityLibrary') {
        param = {
          channelId: this.channelId,
          resourceUrl: img.resourceUrl,
          processId: this.processId,
          resourceType: 2
        }
      }
      const { result } =
        this.fromPage === 'commodityLibrary'
          ? await deleteSkuChannelResource(param)
          : await deleteSkuOptionalResource({ skuId: this.$route.query.id - 0, url: img.resourceUrl })
      if (result) {
        this.$message({
          message: result,
          type: 'success'
        })
        if (this.fromPage === 'commodityLibrary') {
          this.$parent.operationCode[2] = 150
          eventBus.$emit('detailChange', true)
        }
        const index = this.goodsPhotos.skuOptionResources.findIndex((item) => item.id === img.id)
        this.goodsPhotos.skuOptionResources.splice(index, 1)
      }
    },
    advertisingGuidelines() {
      const guideBaseUrl = window.appConfig.operationGuideUrl
      window.open(`${guideBaseUrl}/display/PDF/沃尔玛大卖场商品主图标准.pdf`)
    },
    // 下载图片
    onLoadeImgs(e) {
      this.$emit('onLoadeImgs')
    },
    goJump(channalId) {
      this.$emit('goJumpDown', channalId)
    }
  }
}
</script>
<style lang="scss" scoped>
.content-photo {
  padding: 0 10px;
  .title {
    display: flex;
    &::before {
      content: '*';
      display: inline-block;
      margin-right: 5px;
      color: #f56c6c;
    }
  }
  .title {
    .attention-tips {
      color: #f56c6c;
      .el-button--text {
        color: red;
        text-decoration: underline;
        font-weight: bold;
        margin: 0 5px;
      }
      .el-button--text {
        cursor: pointer;
      }
    }
  }
  .uploadPhoto {
    min-height: 110px;
    padding: 10px 0;
    display: flex;
    flex-wrap: wrap;
    .elImg {
      height: 100px;
      width: 100px;
      display: inline-block;
      margin-right: 10px !important;
      margin-bottom: 10px !important;
      position: relative;
      &:hover .del {
        display: block;
        height: 15px;
      }
      .del {
        line-height: 15px;
        border-radius: 1px;
        padding: 2px 0;
        text-align: center;
        display: none;
        width: 100%;
        height: 0;
        overflow: hidden;
        position: absolute;
        left: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        cursor: pointer;
        color: #fff;
        font-size: 14px;
        transition: linear all 0.5s;
      }
      /deep/ .el-image {
        border-radius: 5px;
        height: 100%;
        width: 100%;
      }
    }
  }
  .tip {
    padding: 0 10px;
    font-size: 14px;
    color: rgb(176, 176, 176);
  }
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader /deep/.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
/deep/ .el-form-item__content {
  line-height: normal;
}
.transition-group {
  display: inline-block;
  height: 100%;
  padding-left: 10px;
}
.attention-tips {
  margin-left: 10px;
  font-size: 10px;
}
</style>
